package note.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynamicProxyText {
    public static void main(String[] args) {
        YangHao yangHao = new YangHao();
        //获取被代理人的字节码类加载器
        ClassLoader classLoader = yangHao.getClass().getClassLoader();
        //获取被代理人的字节码的所有接口集合
        Class<?>[] interfaces = yangHao.getClass().getInterfaces();
        //处理器
        MyInvocationHandler myInvocationHandler = new MyInvocationHandler(yangHao);
        //将获取到的被代理人的字节码类加载器对象传入Proxy.newProxyInstance()中
        //将获取到的被代理人的字节码的所有接口集合传递Proxy.newProxyInstance()中
        Star y = (Star)Proxy.newProxyInstance(classLoader, interfaces,myInvocationHandler);
        double mon = y.show(1000);
        yangHao.sleep();
        System.out.println(mon);
    }
}
class MyInvocationHandler implements InvocationHandler {
    private YangHao yangHao;

    public MyInvocationHandler(YangHao yangHao) {
        this.yangHao = yangHao;
    }

    //代理对象调用方法就会触发invoke方法的执行
    //Object proxy -> y
    //Method method -> show
    //Object[] args -> 1000
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result= null;
       if(method.getName().equals("show")) {
           //前增强
           System.out.println("于飞正给杨昊找了个小电影拍摄，赚了"+(double)args[0]*0.8+"元");
           result = method.invoke(yangHao,(double)args[0]*0.2);
           //后增强
           System.out.println("于飞正帮杨昊把钱存下来");
       }
        return result;
    }
}